{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 条件判断和循环\n",
    "\n",
    "#### if语句\n",
    "\n",
    "#### 语法规则\n",
    "\n",
    "1. 语句是逐个运行\n",
    "2. 块和语句的边界自动检测\n",
    "3. 复合语句 = 首行 + “：” + 缩进语句\n",
    "4. 空白行， 空格以及注释通常都会忽略\n",
    "\n",
    "例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "your age is 20\n",
      "adult\n",
      "END\n"
     ]
    }
   ],
   "source": [
    "age = 20\n",
    "if age >= 18:\n",
    "    print('your age is', age) # 在条件结果里面\n",
    "    print ('adult')           # 在条件结果里面\n",
    "print ('END')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意: Python代码的缩进规则。具有相同缩进的代码被视为代码块，上面的3，4行 print 语句就构成一个代码块（但不包括第5行的print）。如果 if 语句判断为 True，就会执行这个代码块。\n",
    "\n",
    "缩进请严格按照Python的习惯写法：4个空格，不要使用Tab，更不要混合Tab和空格，否则很容易造成因为缩进引起的语法错误。\n",
    "\n",
    "注意: if 语句后接表达式，然后用:表示代码块开始。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "adult\n"
     ]
    }
   ],
   "source": [
    "#我们可以用 if ... 多个elif ... else ... 的结构\n",
    "if age >= 18:\n",
    "    print('adult')\n",
    "elif age >= 13:\n",
    "    print('teenager')\n",
    "elif age >= 3:\n",
    "    print ('kid')\n",
    "else:\n",
    "    print ('baby')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "your score is good\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "练习：\n",
    "如果按照分数划定结果：\n",
    "\n",
    "    90分或以上：excellent\n",
    "\n",
    "    80分或以上：good\n",
    "\n",
    "    60分或以上：passed\n",
    "\n",
    "    60分以下：failed\n",
    "\n",
    "请编写程序根据分数打印结果。\n",
    "\"\"\"\n",
    "score = 85\n",
    "if score >= 90:\n",
    "    print (\"your score is \" + 'excellent')\n",
    "elif score >= 80:\n",
    "    print (\"your score is \" + 'good')\n",
    "elif score >= 60:\n",
    "    print (\"your score is \" + 'passed')\n",
    "else: \n",
    "    print (\"your score is \" + 'failed')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "your score is good\n"
     ]
    }
   ],
   "source": [
    "score = 85\n",
    "if score >= 90:\n",
    "    print('your score is','excellent')\n",
    "elif score >= 80:\n",
    "    print('your score is','good')\n",
    "elif score >= 60:\n",
    "    print('your score is','passsd')\n",
    "else:\n",
    "    print('your score is','failed')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "your score is 85 good\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "练习：\n",
    "如果按照分数划定结果：\n",
    "\n",
    "    90分或以上：excellent\n",
    "\n",
    "    80分或以上：good\n",
    "\n",
    "    60分或以上：passed\n",
    "\n",
    "    60分以下：failed\n",
    "\n",
    "请编写程序根据分数打印结果。\n",
    "\"\"\"\n",
    "score = 85\n",
    "if score >= 90:\n",
    "    print (\"your score is \" + str(score) +  \" excellent\")\n",
    "elif score >= 80:\n",
    "    print (\"your score is \" + str(score) +  ' good')\n",
    "elif score >= 60:\n",
    "    print (\"your score is \" + str(score) +  ' passed')\n",
    "else:\n",
    "    print (\"your score is \" + str(score) +  ' failed')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python之 for循环"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Adam\n",
      "Lisa\n",
      "Bart\n"
     ]
    }
   ],
   "source": [
    "# list或tuple可以表示一个有序集合。如果我们想依次访问一个list中的每一个元素呢？比如 list：\n",
    "\n",
    "L = ['Adam', 'Lisa', 'Bart']\n",
    "print(L[0])\n",
    "print(L[1])\n",
    "print(L[2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果list只包含几个元素，这样写还行，如果list包含1万个元素，我们就不可能写1万行print。\n",
    "\n",
    "这时，循环就派上用场了。\n",
    "\n",
    "Python的 for 循环就可以依次把list或tuple的每个元素迭代出来："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### enumerate()\n",
    "\n",
    "如果你需要索引，可以加上这个，那么会一起输出索引\n",
    "\n",
    "enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列，同时列出数据和数据下标，一般用在 for 循环当中。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "索引(序号）: 0, 值（名字）: Adam\n",
      "索引(序号）: 1, 值（名字）: Lisa\n",
      "索引(序号）: 2, 值（名字）: Bart\n"
     ]
    }
   ],
   "source": [
    "L = ['Adam', 'Lisa', 'Bart']\n",
    "for idx, val in enumerate(L):\n",
    "    print('索引(序号）: {}, 值（名字）: {}'.format(idx, val))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "188\n"
     ]
    }
   ],
   "source": [
    "# 练习： 求 L=[12,28,24,25,99]的总和\n",
    "L=[12,28,24,25,99]\n",
    "total = 0   # 用一个变量记录累加所有值的和\n",
    "for num in L:\n",
    "    total = total + num  # 用循环结果完成累加\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "188\n"
     ]
    }
   ],
   "source": [
    "# 练习： 求 L=[12,28,24,25,99]的总和\n",
    "L=[12,28,24,25,99]\n",
    "total = 0   # 用一个变量记录累加所有值的和\n",
    "for num in L:\n",
    "    total+= num  # 用循环结果完成累加\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "188"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum(L)  # 求和的另一种方式\n",
    "L=[12,28,24,25,99]\n",
    "sum(L)  # 用循环结果完成累加"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python之 while循环\n",
    "和 for 循环不同的另一种循环是 while 循环，while 循环不会迭代 list 或 tuple 的元素，而是根据表达式判断循环是否结束。\n",
    "\n",
    "比如要从 0 开始打印不大于 N 的整数：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n",
      "6\n",
      "7\n",
      "8\n",
      "9\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "N = 10\n",
    "x = 0\n",
    "while x <=N:\n",
    "    print(x)\n",
    "    x = x + 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "while循环每次先判断 x < = N，如果为True，则执行循环体的代码块，否则，退出循环。\n",
    "\n",
    "在循环体内，x = x + 1 会让 x 不断增加，最终因为 x < = N 不成立而退出循环。\n",
    "\n",
    "如果没有这一个语句，while循环在判断 x < = N 时总是为True，就会无限循环下去，变成死循环，所以要特别留意while循环的退出条件。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python之 break退出循环\n",
    "\n",
    "用 for 循环或者 while 循环时，如果要在循环体内直接退出循环，可以使用 break 语句。\n",
    "\n",
    "比如计算1至100的整数和，我们用while来实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "退出循环 101\n",
      "5050\n"
     ]
    }
   ],
   "source": [
    "total = 0\n",
    "x = 1\n",
    "while True:\n",
    "    total = total + x\n",
    "    x = x + 1\n",
    "    if x > 100:\n",
    "        print('退出循环',x)\n",
    "        break\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "退出循环 20\n",
      "1048575\n"
     ]
    }
   ],
   "source": [
    "# 练习：计算 1 + 2 + 4 + 8 + 16 + ... 的前20项的和\n",
    "total = 0\n",
    "x = 0\n",
    "while True:\n",
    "    total = total + 2**x \n",
    "    # print(total)\n",
    "    x = x + 1\n",
    "    # print(x)\n",
    "    if x >19:\n",
    "        print(\"退出循环\",x)\n",
    "        break\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以下程序是一个老师想统计学生的平均分，L里面记录了每个学生的分数，程序最终输出一个浮点数就是学生的平均分。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "平均分： 72.0\n"
     ]
    }
   ],
   "source": [
    "L = [75, 98, 59, 81, 66, 43, 69, 85]\n",
    "total = 0 # 记录总分\n",
    "n = 0     # 记录学生人数\n",
    "for x in L:\n",
    "    n = n + 1\n",
    "    total = total + x\n",
    "print('平均分：',total / n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在老师只想统计及格分数的平均分，就要把 x < 60 的分数剔除掉，\n",
    "\n",
    "这时，利用 continue，可以做到当 x < 60的时候，不继续执行循环体的后续代码，直接进入下一次循环："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "忽略的成绩 59\n",
      "忽略的成绩 43\n",
      "79.0\n"
     ]
    }
   ],
   "source": [
    "L = [75, 98, 59, 81, 66, 43, 69, 85]\n",
    "total = 0\n",
    "n = 0\n",
    "for x in L:\n",
    "    if x < 60:\n",
    "        print('忽略的成绩', x)\n",
    "        continue  # 到下一个循环，下面的代码不执行\n",
    "    total = total + x\n",
    "    n = n + 1\n",
    "print(total / n)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "3\n",
      "5\n",
      "7\n",
      "9\n",
      "11\n",
      "13\n",
      "15\n",
      "17\n",
      "19\n",
      "21\n",
      "23\n",
      "25\n",
      "27\n",
      "29\n",
      "31\n",
      "33\n",
      "35\n",
      "37\n",
      "39\n",
      "41\n",
      "43\n",
      "45\n",
      "47\n",
      "49\n",
      "51\n",
      "53\n",
      "55\n",
      "57\n",
      "59\n",
      "61\n",
      "63\n",
      "65\n",
      "67\n",
      "69\n",
      "71\n",
      "73\n",
      "75\n",
      "77\n",
      "79\n",
      "81\n",
      "83\n",
      "85\n",
      "87\n",
      "89\n",
      "91\n",
      "93\n",
      "95\n",
      "97\n",
      "99\n",
      "2500\n"
     ]
    }
   ],
   "source": [
    "# 改写下面程序，计算0-100的奇数和\n",
    "total = 0\n",
    "for i in range(0, 101):\n",
    "    if i % 2 == 0: #   ‘%’是求余数\n",
    "        continue\n",
    "    print(i)\n",
    "    total += i  # 和 total = total + i 是一样的意思\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python之 多重循环"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A1\n",
      "A2\n",
      "A3\n",
      "B1\n",
      "B2\n",
      "B3\n",
      "C1\n",
      "C2\n",
      "C3\n"
     ]
    }
   ],
   "source": [
    "for x in ['A', 'B', 'C']:\n",
    "    for y in ['1', '2', '3']:\n",
    "        print (x + y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12 13 14 15 16 17 18 19 \n",
      "23 24 25 26 27 28 29 \n",
      "34 35 36 37 38 39 \n",
      "45 46 47 48 49 \n",
      "56 57 58 59 \n",
      "67 68 69 \n",
      "78 79 \n",
      "89 \n",
      "\n",
      "完成\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "对100以内的两位数，请使用一个两重循环打印出所有十位数数字比个位数数字小的数，例如，23（2 < 3）\n",
    "\"\"\"\n",
    "for x in [1,2,3,4,5,6,7,8,9]: # 十位上的数，不包括0\n",
    "    \n",
    "    for y in [0,1,2,3,4,5,6,7,8,9]: # 个位上的数\n",
    "        # 这里是第二个循环结构\n",
    "        if x < y:\n",
    "            print(str(x)+str(y), end= ' ') # end是不换行，以空格为结尾\n",
    "    \n",
    "    # 这里是第一个循环结构\n",
    "    print() # 默认打印都是换行为结尾 \n",
    "print('完成')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
